package com.takeshequ.friends;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.takeshequ.Constants;
import com.utils.HttpClientUtils;
import com.utils.HttpClientUtils.HttpResponseHandler;

public class BaseData {

	private static Gson gson;
	private static Map<String, List<Friend>> friendsMap = new HashMap<String, List<Friend>>();
	public static List<Friend> friendList = new ArrayList<Friend>();

	static {
		gson = new Gson();
	}

	public static void init() {
		Map<String, String> params = new HashMap<String, String>();
		params.put("pageNumber", "1");
		params.put("memberId", Constants.memberId);
		
		HttpClientUtils.get("listFriend", params, new HttpResponseHandler() {
			@Override
			public void handler(String response) {
				try {
					JSONObject jsonObject = new JSONObject(response);
					List<Friend> userInformations = gson.fromJson(
							jsonObject.getString("memberList"),
							new TypeToken<List<Friend>>() {
							}.getType());
					friendList = userInformations;
					dealWithFirstChar(userInformations);

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});

	}

	private static void dealWithFirstChar(List<Friend> friends) {
		TreeMap<String, List<Friend>> treeMap = new TreeMap<String, List<Friend>>(
				new Comparator<String>() {

					@Override
					public int compare(String lhs, String rhs) {
						return lhs.compareToIgnoreCase(rhs);
					}
				});
		for (Friend friend : friends) {
			String firstChar = friend.getNickNameFirstChar();
			if (treeMap.containsKey(firstChar)) {
				treeMap.get(firstChar).add(friend);
			} else {
				List<Friend> friendsSubList = new ArrayList<Friend>();
				friendsSubList.add(friend);
				treeMap.put(firstChar, friendsSubList);
			}
		}
		friendsMap = treeMap;

	}

	public static Map<String, List<Friend>> getFriends() {
		return friendsMap;
	}

	public static String getNickName(String memberId) {
		for (Friend friend : friendList) {
			if (friend.getMemberId().equals(memberId)) {
				return friend.getNickName();
			}
		}
		return "";
	}

	public static Friend getFriend(String memberId) {
		for (Friend friend : friendList) {
			if (friend.getMemberId().equals(memberId)) {
				return friend;
			}
		}
		return null;
	}

}
